package com.foreveross.mofang.serviceconsole.application.impl.core;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Named;

import org.openkoala.koala.auth.core.domain.User;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.foreveross.mofang.serviceconsole.application.core.GroupApplication;
import com.foreveross.mofang.serviceconsole.application.dto.GroupDTO;
import com.foreveross.mofang.serviceconsole.core.Group;

/**
 * 渠道及任务组基础层实现
 * 
 * @author fb
 *
 */
@Named
@Transactional
public class GroupApplicationImpl implements GroupApplication {

	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public GroupDTO getGroup(Long id) {
		Group group = Group.load(Group.class, id);
		GroupDTO groupDTO = new GroupDTO();  
		// 将domain转成VO
		groupDTO.domain2Dto(group); 
		return groupDTO;
	}  
	
	public void saveGroup(GroupDTO groupDTO, User loginUser, Class<? extends Group> clazz) throws InstantiationException, IllegalAccessException {
		Group group = clazz.newInstance();
		groupDTO.dto2Domain(group);
		group.setUser(loginUser);
		group.setLastUpdateUser(loginUser);
		group.save(clazz);
		
	}
	
	public void updateGroup(GroupDTO groupDTO, User loginUser) {
		Group group = Group.get(Group.class, groupDTO.getId());
		groupDTO.dto2Domain(group);
		group.setLastUpdateUser(loginUser);
		group.setLastUpdate(new Date());
		group.update(group.getClass());
	}
	
	public void removeGroup(Long id, User loginUser) {
		this.removeGroups(new Long[] { id }, loginUser);
	}
	
	public void removeGroups(Long[] ids, User loginUser) {
		for (int i = 0; i < ids.length; i++) {
			Group group = Group.load(Group.class, ids[i]);
			group.remove(loginUser);
		}
	}
	
	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public List<GroupDTO> getRoots(Class<? extends Group> clazz) {
		List<GroupDTO> list = new ArrayList<GroupDTO>();
		List<Group> all = Group.getAllRoots(clazz);
		for (Group group : all) {
			if (group.getRemoved()) {
				continue;
			}
			
			GroupDTO groupDTO = new GroupDTO();
			groupDTO.domain2Dto(group);
			list.add(groupDTO);
		}
		return list;
	}
	
	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public List<GroupDTO> findAllGroup() {
		List<GroupDTO> list = new ArrayList<GroupDTO>();
		List<Group> all = Group.findAll(Group.class);
		for (Group group : all) {
			if (group.getRemoved()) {
				continue;
			}
			
			GroupDTO groupDTO = new GroupDTO(false);
			groupDTO.domain2Dto(group);
			list.add(groupDTO);
		}
		return list;
	}
}
